package com.yaosheng.thread.lock;

import java.util.concurrent.CountDownLatch;

/**
 * Created by yaosheng on 2021/6/30.
 * CountDownLatch:等待线程结束进行某一操作
 */
public class TestCountDownLatch {

    public static void main(String[] args) {
        usingCountDownLatch ();
    }

    private static void usingCountDownLatch(){

        Thread[] thread = new Thread[100];
        CountDownLatch latch = new CountDownLatch (thread.length);

        for(int i=0;i<thread.length;i++){
            thread[i] = new Thread ( () -> {
                int result = 0;
                for(int j=0;j<10000;j++) result += j;
                latch.countDown ();
            });
        }

        for(int i=0;i<thread.length;i++){
            thread[i].start ();
        }

        try{
            latch.await();
        }catch (InterruptedException e){
            e.printStackTrace ();
        }

        System.out.println ("end latch");
    }

    private static void usingJoin(){

        Thread[] thread = new Thread[100];

        for(int i=0;i<thread.length;i++){
            thread[i] = new Thread ( () -> {
                int result = 0;
                for(int j=0;j<10000;j++) result += j;
            });
        }
    }
}
